// 后端 API 封装
// 所有接口基于 http://127.0.0.1:8000/api/

export const API_BASE = 'http://127.0.0.1:8000/api';

export async function getGpuStatus() {
  const res = await fetch(`${API_BASE}/status/gpu`);
  if (!res.ok) throw new Error('获取GPU状态失败');
  return res.json();
}

export async function getModels() {
  const res = await fetch(`${API_BASE}/models/`);
  if (!res.ok) throw new Error('获取模型列表失败');
  return res.json();
}

export async function uploadJobFile(file: File) {
  const form = new FormData();
  form.append('file', file);
  const res = await fetch(`${API_BASE}/jobs/upload`, {
    method: 'POST',
    body: form,
  });
  if (!res.ok) throw new Error('上传文件失败');
  return res.json();
}

export async function startJob(params: { taskType: string; dataFile: string; params?: any; modelId?: string }) {
  const res = await fetch(`${API_BASE}/jobs/start`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  if (!res.ok) throw new Error('启动任务失败');
  return res.json();
}

export async function getJobStatus(jobId: string) {
  const res = await fetch(`${API_BASE}/jobs/${jobId}/status`);
  if (!res.ok) throw new Error('获取任务状态失败');
  return res.json();
}

export async function stopJob(jobId: string) {
  const res = await fetch(`${API_BASE}/jobs/${jobId}/stop`, { method: 'POST' });
  if (!res.ok) throw new Error('停止任务失败');
  return res.json();
}

export async function predict(image: File, modelId: string) {
  const form = new FormData();
  form.append('image', image);
  form.append('model_id', modelId);
  const res = await fetch(`${API_BASE}/inference/predict`, {
    method: 'POST',
    body: form,
  });
  if (!res.ok) throw new Error('推理失败');
  return res.json();
}

export async function queryData(sql: string) {
  const res = await fetch(`${API_BASE}/data/query`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ sql }),
  });
  if (!res.ok) throw new Error('SQL查询失败');
  return res.json();
}

export async function analyze(analysisType: string, data: any) {
  const res = await fetch(`${API_BASE}/ai/analyze`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ analysisType, data }),
  });
  if (!res.ok) throw new Error('AI分析失败');
  return res.json();
}
